import json
import ast

from django.db import transaction
from django.db.models import F
from rest_framework.views import APIView, Response, status
from rest_framework import viewsets, mixins
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
from rest_framework import filters
from django_filters.rest_framework import DjangoFilterBackend

from apps.common.account.models import Account
from apps.pollution.models import Category, Question, Answer
from apps.pollution.utils import upload_file_to_oss
from .serializers import QuestionSerializer, AnswerSerializer, CompanySerializer, AnswerListSerializer
from .filters import AccountFilter, AnswerFilter
from utils.common import Pagination


class QuestionViewSet(mixins.ListModelMixin,
                      viewsets.GenericViewSet):
    queryset = Question.objects.all().order_by('sort_num')
    serializer_class = QuestionSerializer
    filter_backends = (DjangoFilterBackend, filters.OrderingFilter)

    def list(self, request, *args, **kwargs):
        company_name = request.query_params.get('company_name', None)
        if not company_name:
            return Response({'message': '需要企业名称'}, status=status.HTTP_400_BAD_REQUEST)
        choices = [
            {'name': '完成', 'value': 0},
            {'name': '未完成', 'value': 1},
            {'name': '不涉及', 'value': 2},
        ]
        queryset = Question.objects.all().order_by('sort_num').values()
        cate_ids = [i['category_id'] for i in queryset]
        cate_objs = Category.objects.filter(id__in=cate_ids).order_by('sort_num').values()
        cate_children = {i['id']: [] for i in cate_objs}
        company_obj = Account.objects.filter(username=company_name).values('id', 'ying_ji', 'jian_kong').first()
        yingji, jiankong = None, None
        if company_obj:
            yingji = company_obj['ying_ji']
            jiankong = company_obj['jian_kong']
        for i in queryset:
            i['choices'] = choices
            if i['category_id'] == 6 and yingji:    # 第5个指标需要做应急预案的
                i['choices'] = [
                    {'name': '完成', 'value': 0},
                    {'name': '未完成', 'value': 1},
                ]
            if i['category_id'] == 7 and jiankong:  # 第六个指标要在线监控
                i['choices'] = [
                    {'name': '完成', 'value': 0},
                    {'name': '未完成', 'value': 1},
                ]
            cate_children[i['category_id']].append(i)
        res_data = []
        for i in cate_objs:
            i['children'] = cate_children[i['id']]
            res_data.append(i)

        return Response(res_data)


class AnswerViewSet(mixins.CreateModelMixin,
                    mixins.ListModelMixin,
                    mixins.UpdateModelMixin,
                    viewsets.GenericViewSet):
    queryset = Answer.objects.all().order_by('-updated_time')
    serializer_class = AnswerSerializer
    filter_class = AnswerFilter
    pagination_class = Pagination
    filter_backends = (DjangoFilterBackend, filters.OrderingFilter)

    def get_serializer_class(self):
        if self.action == 'list':
            return AnswerListSerializer
        return self.serializer_class

    @action(methods=['post'], detail=False, url_path='upload_img')
    def upload_img_to_oss(self, request, pk=None):
        # 上传图片到阿里云oss
        company_name = request.data.get('company_name', None)
        if not company_name:
            return Response({'message': '需要企业名称'}, status=status.HTTP_400_BAD_REQUEST)
        image = request.data.get('image', None)
        if not image:
            return Response({'message': '需要图片'}, status=status.HTTP_400_BAD_REQUEST)
        file_name = f"{company_name}-{image.name}"
        file_path = upload_file_to_oss(image, file_name)
        if not file_path:
            return Response({'message': '图片上传失败'}, status=status.HTTP_400_BAD_REQUEST)
        return Response({'data': file_path})

    @action(methods=['get'], detail=False, url_path='percentage_complete')
    def get_percentage_complete(self, request, pk=None):
        #  获取每个指标的全镇完成率
        queryset = Question.objects.all().order_by('sort_num').values('id', 'category_id', category_name=F('category__name'))

        ying_ji_company_name = Account.objects.filter(is_company=True, batch_num=2, ying_ji=True)\
            .values_list('username', flat=True)

        jian_kong_company_name = Account.objects.filter(is_company=True, batch_num=2, jian_kong=True) \
            .values_list('username', flat=True)

        company_count = Account.objects.filter(is_company=True, batch_num=2).count()

        answers_qs = Answer.objects.filter(batch_num=2).values('answer', 'company_name')

        answers_count = Answer.objects.filter(batch_num=2).count()

        # 获取一级指标以及子指标的id数组
        # 格式如下：
        """
         question_list = [
           {'id': 1, 'name': '指标名', 'child':[1, 2, 3]}, '''
         ]
        """

        question_list = []
        qs_dict = {'id': None, 'child': []}  # 构造对象格式
        for qs in queryset:  # 循环子题目
           if qs_dict['id'] == None:  # 如果为空，则将值写入对象
                qs_dict['id'] = qs['category_id']
                qs_dict['name'] = qs['category_name']
                qs_dict['child'].append(qs['id'])
           else:  # 如果不为空，则判断父id是否相同
               if qs['category_id'] == qs_dict['id']:  # 相同则将子id加入
                   qs_dict['child'].append(qs['id'])
               else:  # 不相同则将对象加入数组，并重新构造对象
                   question_list.append(qs_dict)
                   qs_dict = {'id': None, 'child': []}
                   qs_dict['id'] = qs['category_id']
                   qs_dict['name'] = qs['category_name']
                   qs_dict['child'].append(qs['id'])
        question_list.append(qs_dict)
        # 获取每个一级指标的公司完成数
        # 格式如下：
        """
         result_qs = [
           {'id': 1, 'name': '指标名', 'count':0}, '''
         ]
        """

        result_qs = []
        for question in question_list:  # 循环9个一级指标
            result_dict = {'id': question['id'], 'name': question['name']}  # 构造对象
            count = 0  # 初始化完成公司数
            sum = 0  # 初始化已填的公司数
            if question['id'] not in [6, 7]:
                sum = answers_count
                for answer in answers_qs:  # 循环已填的公司答案
                    flag = 0  # 是否没完成
                    for i in question['child']:  # 循环一级指标下的小指标
                        if (answer['answer'][str(i)] == '1') or (
                                answer['answer'][str(i)] == 1):  # 如有一个小指标未完成， 则该公司的该指标未完成，退出该循环
                            flag = 1
                            break
                    if flag == 0:  # 如等于，该公司该指标已完成， 完成公司数count+1
                        count += 1
            elif question['id'] == 6:
                for answer in answers_qs:  # 循环已填的公司答案
                    if answer['company_name'] in ying_ji_company_name:
                        sum += 1
                        flag = 0  # 是否没完成
                        for i in question['child']:  # 循环一级指标下的小指标
                            if (answer['answer'][str(i)] == '1') or (
                                    answer['answer'][str(i)] == 1):  # 如有一个小指标未完成， 则该公司的该指标未完成，退出该循环
                                flag = 1
                                break
                        if flag == 0:  # 如等于，该公司该指标已完成， 完成公司数count+1
                            count += 1
            elif question['id'] == 7:
                for answer in answers_qs:  # 循环已填的公司答案
                    if answer['company_name'] in jian_kong_company_name:
                        sum += 1
                        flag = 0  # 是否没完成
                        for i in question['child']:  # 循环一级指标下的小指标
                            if (answer['answer'][str(i)] == '1') or (
                                    answer['answer'][str(i)] == 1):  # 如有一个小指标未完成， 则该公司的该指标未完成，退出该循环
                                flag = 1
                                break
                        if flag == 0:  # 如等于，该公司该指标已完成， 完成公司数count+1
                            count += 1
            result_dict['count'] = count  # 向对象加入该指标的公司完成数
            result_dict['sum'] = sum
            result_qs.append(result_dict)

        res_list = [{'id': None, 'data': ['指标', '单任务平均完成率', '已下现场的企业数',  '需开展整治的任务数（家）']}]
        for res in result_qs:
            res_dict = {'id': res['id'], 'data': [res['name']]}
            count = res['count']
            sum = res['sum']

            if sum == 0:
                res_dict['data'].append(0)
            else:
                rate = "%.2f%%" % ((count / sum) * 100)
                res_dict['data'].append(rate)

            res_dict['data'].append(sum)

            if res['id'] not in [6, 7]:
                res_dict['data'].append(company_count)
            elif res['id'] == 6:  # 该指标需开展整治的公司数
                res_dict['data'].append(len(ying_ji_company_name))
            elif res['id'] == 7:  # 该指标需开展整治的公司数
                res_dict['data'].append(len(jian_kong_company_name))
            res_list.append(res_dict)

        return Response({'data': res_list, 'colWidths': ['350', '300', '300', '350']})


class CompanyViewSet(mixins.ListModelMixin,
                     viewsets.GenericViewSet):
    queryset = Account.objects.filter(is_company=True, is_write=False).order_by('id')
    serializer_class = CompanySerializer
    filter_class = AccountFilter
    filter_backends = (DjangoFilterBackend, filters.OrderingFilter)
    # permission_classes = [IsAuthenticated]
